package com.honeycomb.user.control;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.honeycomb.common.PositionInfo;
import com.honeycomb.common.ResourceManager;
import com.honeycomb.user.dto.UserLoginInfo;
import com.honeycomb.user.dto.UserinfoDto;
import com.honeycomb.user.dto.UserinfoDto.Sex;
import com.honeycomb.user.service.UserService;
import com.honeycomb.utils.CodeImgGenerater;
import com.honeycomb.utils.ErrorMsgConstants;
import com.honeycomb.utils.MyDateDTTM;
import com.honeycomb.utils.SystemConstants;

import static com.honeycomb.common.ParamConverter.*;


/**
 * 用户控制器
 * 
 * @author Wangyu
 */
@Controller
@RequestMapping("user/")
public class UserControl {
	
	protected Logger logger = LogManager.getLogger(this.getClass());

	@Resource
	private UserService userService;
	
	@RequestMapping("loginInfo")
	public String loginInfo(HttpServletResponse response){
		
		return "login";
		//return "user/login";//和上一句的区别：上一个是跳转到默认根目录（忽略WEB-INF）下的login，本句是跳转到WEB-INF下的user中的login.jsp
	}
	

	/*
	 * @author zcw
	 * 加入中间跳转页面
	 * */
	@RequestMapping("infoCenter")
	public String infoCenter(HttpServletRequest request, HttpServletResponse response) {
		String login_id = assertNotEmpty(request.getParameter("userLoginEmail"));
		String psw = assertNotEmpty(request.getParameter("userLoginPassword"));
		String ipcity = assertNotNull(request.getParameter("ipcity"));

		UserLoginInfo loginInfo = new UserLoginInfo(assertMaxLength(assertEmailString(login_id), SystemConstants.LENGTH_LIMIT_USER_LOGINID), assertMaxLength(psw, SystemConstants.LENGTH_LIMIT_USER_PASSWORD) );
		UserinfoDto userInfo = userService.doCheckUserIsLegal(loginInfo);
		if (userInfo != null) {
			request.getSession().setAttribute(SystemConstants.LOGINUSER_SESSION_NAME, userInfo);
			
			loginInfo.setPsw(null);
			request.getSession().setAttribute(SystemConstants.LOGINUSER_SESSION_LOGIN_INFO, loginInfo);
			
			Stack<PositionInfo> favourPositions = userService.getFavourPositions(userInfo.getUserId());
			request.getSession().setAttribute(SystemConstants.LOGINUSER_SESSION_FAVOUR_POSITIONS, favourPositions);
			
			// 如果传入的ipcity为空，则表示未能获取到用户ip所在城市。
			if (!ipcity.equals("")) {
				if (logger.isDebugEnabled()) {
					logger.debug("ipcity is found and set:" + ipcity);
				}
				request.getSession().setAttribute(SystemConstants.LOGINUSER_SESSION_IPCITY, ipcity);
			}
			else {
				logger.warn("ipcity can not be found.");
			}
			
			return "infocenter";
		} else {
			request.setAttribute("message", ErrorMsgConstants.ERR_USER_LOGIN_WRONG);
			return "login";
		}
	}
	/*
	 * 登陆信息的销毁
	 * 
	 */
	@RequestMapping("sessionRemove")
	public String  sessionRemove(HttpServletRequest request, HttpServletResponse response) {
		
		request.getSession().removeAttribute(SystemConstants.LOGINUSER_SESSION_NAME);
		return "login";
	}
	
	@RequestMapping("mainInfo")
	public String mainInfo(HttpServletRequest request, HttpServletResponse response) {
		if (request.getSession().getAttribute(SystemConstants.LOGINUSER_SESSION_NAME) != null){
			return "main";
		} else {
			request.setAttribute("message", ErrorMsgConstants.ERR_LOGIN);
			return "login";
		}
	}
	
	@RequestMapping("registInfo")
	public String registInfo(HttpServletRequest request, HttpServletResponse reponse) throws UnsupportedEncodingException{
		String ipcity = assertNotNull(request.getParameter("ipcity"));
		ipcity = java.net.URLDecoder.decode(ipcity, "UTF-8");
		
		if (!ipcity.equals("")) {
			if (logger.isDebugEnabled()) {
				logger.debug("ipcity is found and set:" + ipcity);
			}
			request.getSession().setAttribute(SystemConstants.LOGINUSER_SESSION_IPCITY, ipcity);
		}
		else {
			logger.warn("ipcity can not be found.");
		}
		
		return "regist";
	}
	
	@RequestMapping("ajaxuserRegistcheck")
	@ResponseBody
	public boolean userRegistcheck(HttpServletRequest request, HttpServletResponse response) {
		String userRegistyancheck = assertNotEmpty(request.getParameter("userRegistyancheck"));
		
		String str = (String)request.getSession().getAttribute("code");
	
		boolean flag = false;
		if(str.equals(userRegistyancheck))
		{
			flag = true;
		}
			
		return flag	;
	} 
	
	@RequestMapping("ajaxCheckUserRegistEmailExist")
	@ResponseBody
	public boolean ajaxCheckUserRegistEmailExist(HttpServletRequest request, HttpServletResponse response) {
		String userRegistEmail = assertNotEmpty(request.getParameter("userRegistEmail"));
		return userService.doCheckEmailAlreadyExist(userRegistEmail.trim()) ;
	}
	
	
	@RequestMapping("addregist")
	public String addregist(HttpServletRequest request, HttpServletResponse response) {
		String registMail = assertNotEmpty(request.getParameter("userRegistEmail")).trim();
		String nickName = assertNotEmpty(request.getParameter("userRegistNickname")).trim();
		String password = assertNotEmpty(request.getParameter("userRegistPassword"));
		String registSex = assertNotEmpty(request.getParameter("userRegistSex"));
		String registBirthday = assertNotEmpty(request.getParameter("userRegistBirthday"));
		String registImage = assertNotEmpty(request.getParameter("imgPath"));
		String statement = assertNotNull(request.getParameter("statement")).trim();
		
		UserLoginInfo loginInfo = new UserLoginInfo(assertMaxLength(assertEmailString(registMail),SystemConstants.LENGTH_LIMIT_USER_LOGINID), assertMaxLength(password, SystemConstants.LENGTH_LIMIT_USER_PASSWORD));
		
		UserinfoDto userInfo = new UserinfoDto(ResourceManager.generateNumberID() );
		userInfo.setUserNickname(assertMaxLength(convertToHtmlCapableString(nickName), SystemConstants.LENGTH_LIMIT_USER_NICKNAME));
		userInfo.setUserSex(Sex.getSex(registSex));
		userInfo.setUserRegistDttm(new MyDateDTTM());
		userInfo.setUserBirthday(MyDateDTTM.decodeFromDTString(registBirthday) );
		userInfo.setUserHeadImagUrl(assertMaxLength(registImage,  SystemConstants.LENGTH_LIMIT_USER_IMAGEURL));
		userInfo.setUserRegistIp(request.getRemoteAddr());
		userInfo.setStatement(isNullOrEmpty(statement) ? "个人签名" : assertMaxLength(convertToHtmlCapableString(statement), SystemConstants.LENGTH_LIMIT_USER_STATEMENT) );
		
		userInfo = userService.doAddUserinfo(loginInfo, userInfo);
		loginInfo.setPsw(null);
		request.getSession().setAttribute(
					SystemConstants.LOGINUSER_SESSION_NAME, userInfo);
		request.getSession().setAttribute(SystemConstants.LOGINUSER_SESSION_LOGIN_INFO, loginInfo);
		request.getSession().setAttribute(SystemConstants.LOGINUSER_SESSION_FAVOUR_POSITIONS, new Stack<PositionInfo>());
		return "infocenter";
	}
	
	@RequestMapping("checkcode")
	@ResponseBody
	public void checkcode(HttpServletRequest request, HttpServletResponse response){

		CodeImgGenerater codeGenerator = new CodeImgGenerater();
		char[] codeChars = codeGenerator.createRandomChars();
		request.getSession().setAttribute("code", String.valueOf(codeChars));
		
		OutputStream outStream = null;
		try {
			outStream = response.getOutputStream();
			ImageIO.write(codeGenerator.creatImageFromChars(codeChars), "JPEG", outStream);
			outStream.flush();
		}
		catch(IOException ex) {
			throw new IllegalStateException(ex);
		}
		finally {
			try {
				if (outStream != null) {
					outStream.close();
				}
			}
			catch(IOException exp) {
				logger.warn("Fail to close response's outputStream.", exp);
			}
			outStream = null;
		}
	}
	
	@RequestMapping("userInfoModifiy")
	public String userInfoModifiy(HttpServletRequest request, HttpServletResponse response) {
		return "userInfoModifiy";
	}
	
	
	@RequestMapping("ajaxuserModifyPassword")
	@ResponseBody
	public boolean ajaxuserModifyPassword(HttpServletRequest request, HttpServletResponse response) {
		UserLoginInfo loginInfo = (UserLoginInfo)((UserLoginInfo)request.getSession().getAttribute(SystemConstants.LOGINUSER_SESSION_LOGIN_INFO)).clone();
		String userModifyPassword = assertNotEmpty(request.getParameter("userModifyPassword"));
		loginInfo.setPsw(assertMaxLength(userModifyPassword, SystemConstants.LENGTH_LIMIT_USER_PASSWORD));
		boolean flag = userService.doCheckUserIsLegal(loginInfo) == null ? false : true ;
		
		return flag;
	}
	
	
	@RequestMapping("ajaxModify01")
	@ResponseBody
	public boolean ajaxModify01(HttpServletRequest request, HttpServletResponse response) {
		String userModifyNickname = assertNotEmpty(request.getParameter("userModifyNickname")).trim();
		String userModifyBirthday = assertNotEmpty(request.getParameter("userModifyBirthday"));
		String user_headurl = assertNotEmpty(request.getParameter("headUrl"));
		String user_statement = assertNotNull(request.getParameter("statement")).trim();
		
		UserinfoDto userinfo = (UserinfoDto)request.getSession().getAttribute(SystemConstants.LOGINUSER_SESSION_NAME);

		UserinfoDto newInfo = userinfo.clone();
		newInfo.setUserNickname(assertMaxLength(convertToHtmlCapableString(userModifyNickname), SystemConstants.LENGTH_LIMIT_USER_NICKNAME));
		newInfo.setUserHeadImagUrl(assertMaxLength(user_headurl, SystemConstants.LENGTH_LIMIT_USER_IMAGEURL));
		newInfo.setUserBirthday(MyDateDTTM.decodeFromDTString(userModifyBirthday) );
		newInfo.setStatement(isNullOrEmpty(user_statement) ? "个人签名" : assertMaxLength(convertToHtmlCapableString(user_statement), SystemConstants.LENGTH_LIMIT_USER_STATEMENT) );
		if (userService.doUpdate01(newInfo)) {
			request.getSession().setAttribute(SystemConstants.LOGINUSER_SESSION_NAME, newInfo);
			return true;
		}
		else {
			return false;
		}
	}
	
	@RequestMapping("ajaxModify02")
	@ResponseBody
	public boolean ajaxModify02(HttpServletRequest request, HttpServletResponse response){
		boolean flag = false;
		String userNewPassword = assertNotEmpty(request.getParameter("userNewPassword"));

		UserinfoDto userinfo = (UserinfoDto)request.getSession().getAttribute(SystemConstants.LOGINUSER_SESSION_NAME);
		UserLoginInfo loginInfo = new UserLoginInfo();
		loginInfo.setPsw(assertMaxLength(userNewPassword, SystemConstants.LENGTH_LIMIT_USER_PASSWORD));

		flag = userService.doUpdate02(userinfo.getUserId(), loginInfo);
		return flag;
	}
	
	@RequestMapping("ajaxAddFavorPosi")
	@ResponseBody
	public Map<String, Object> ajaxAddFavourPosition(HttpServletRequest request, HttpServletResponse response) {
		UserinfoDto userInfoDto = (UserinfoDto)request.getSession().getAttribute(SystemConstants.LOGINUSER_SESSION_NAME);
		String mapX = assertNotEmpty(request.getParameter("mapX"));
		String mapY = assertNotEmpty(request.getParameter("mapY"));
		String mapAddr = assertNotEmpty(request.getParameter("mapAddr"));
		String mapProviderIdPropName = assertNotEmpty(request.getParameter("mapProviderIdProperty"));
		
		PositionInfo positionInfo = new PositionInfo();
		positionInfo.setAddress(assertMaxLength(convertToHtmlCapableString(mapAddr), SystemConstants.LENGTH_LIMIT_POSITION_ADDR));
		positionInfo.setMapProviderId(convertToInteger(mapProviderIdPropName) );
		positionInfo.setLongitude(convertToDouble(mapX));
		positionInfo.setLatitude(convertToDouble(mapY));
		positionInfo.setType(PositionInfo.PositionType.FAVOUR);
		userService.doAddPosition(userInfoDto.getUserId(), positionInfo);
		
		Map<String, Object> returnJson = new HashMap<String, Object>();
		returnJson.put("result", SystemConstants.AJAX_SUCCESS);
		return returnJson;
	}
	
	@RequestMapping("SuccessModify")
	public String SuccessModify(HttpServletRequest request, HttpServletResponse response) {
		UserinfoDto userInfoDto = (UserinfoDto)request.getSession().getAttribute(SystemConstants.LOGINUSER_SESSION_NAME);
		try{
			UserinfoDto userm = userService.getUser(userInfoDto.getUserId());
		
			request.getSession().setAttribute(
					SystemConstants.LOGINUSER_SESSION_NAME, userm);
		}
		catch(Exception e){
			request.setAttribute("erroMessage", ErrorMsgConstants.ERR_USER);
		}
		return "main";
	}
	
	@RequestMapping("ajaxSetPosition")
	@ResponseBody
	public Map<String, Object> ajaxSetUserPosition(HttpServletRequest request) {
		String userMapXStr = assertNotEmpty(request.getParameter("userMapX"));
		String userMapYStr = assertNotEmpty(request.getParameter("userMapY"));
		String userMapAddrStr = assertNotEmpty(request.getParameter("userMapAddr"));
		String userMapProviderIdStr = assertNotEmpty(request.getParameter("userMapProvider"));
		
		if (logger.isDebugEnabled()) {
			logger.debug("ajaxSetUserPosition entered, " + ", userMapXStr=" + userMapXStr + ", userMapYStr=" + userMapYStr + ", userMapAddrStr=" + userMapAddrStr + ", userMapProviderIdStr=" + userMapProviderIdStr);
		}
		
		double userMapX = convertToDouble(userMapXStr);
		double userMapY = convertToDouble(userMapYStr);
		String userMapAddr = assertMaxLength(convertToHtmlCapableString(userMapAddrStr), SystemConstants.LENGTH_LIMIT_POSITION_ADDR);
		Integer userMapProviderId = convertToInteger(userMapProviderIdStr);
		
		request.getSession().setAttribute(SystemConstants.LOGINUSER_SESSION_CURRENT_POSITION, new PositionInfo(userMapX, userMapY, userMapAddr, userMapProviderId));
	
		Map<String, Object> returnJson = new HashMap<String, Object>();
		returnJson.put("result", SystemConstants.AJAX_SUCCESS);
		
		return returnJson;
	}
	
}
